package com.devunion.bogdan.view.project.actions;

import com.devunion.bogdan.view.project.dialogs.TextEntryDialog;
import com.devunion.bogdan.view.project.dialogs.FileNameTransformer;
import com.devunion.bogdan.view.project.dialogs.ActionResult;
import com.devunion.bogdan.view.util.i18n;
import com.devunion.bogdan.model.project.PaperCreationException;
import com.devunion.bogdan.model.project.Paper;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.*;

/**
 * @author Viktar Liaskovich
 */
public abstract class AbstractNewEntryAction extends AbstractProjectAction {
    protected static TextEntryDialog textEntryDialog;
    protected Paper paper;
    protected FileNameTransformer fileNameTransformer;

    public AbstractNewEntryAction(String name) {
        super(name);
    }

    public void actionPerformed(ActionEvent e) {
        Frame parentFrame = (Frame) SwingUtilities.getWindowAncestor((Component) e.getSource());

        Paper parentEntry = getPaper(e);

        initTextEntryDialog(parentFrame);

//        textEntryDialog.setCurrentDir(parentEntry.getEntryFile());
        textEntryDialog.setFileNameTransformer(fileNameTransformer);

        textEntryDialog.setVisible(true);

        if (textEntryDialog.getActionResult() == ActionResult.OK) {

            String fileName = textEntryDialog.getText();

            try {
                paper = createEntry(parentEntry, fileName);
            } catch (PaperCreationException e1) {
                JOptionPane.showMessageDialog(parentFrame, e1.getMessage(), "File creation Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

//            ((ProjectModule) parentEntry).addPaper(paper);
        } else {
            paper = null;
        }
    }

    protected abstract Paper createEntry(Paper parentEntry, String fileName) throws PaperCreationException;

    private void initTextEntryDialog(Frame parentFrame) {
        if (textEntryDialog == null) {
            textEntryDialog = new TextEntryDialog(parentFrame);
            textEntryDialog.setTitle(i18n.getString("Project.Dialogs.NewFile"));
            textEntryDialog.setMessage(i18n.getString("Project.Dialogs.EnterFileName"));
            textEntryDialog.setModal(true);
            textEntryDialog.setLocationRelativeTo(null);
        }

    }
}
